<template>
  <div class="camera-device-page" v-loading="loading">
    <div class="page-header">
      <div class="title">
        <span>{{ show === 'device' ? '设备管理' : '通道管理' }}</span>
        <el-button 
          v-if="show === 'channel'" 
          type="primary" 
          plain 
          size="small"
          @click="changeShow('device')"
        >
          设备管理
        </el-button>
        <el-button 
          v-if="show === 'device'" 
          type="primary" 
          size="small" 
          @click="insertDevice"
        >
          添加设备
        </el-button>
      </div>
    </div>
    
    <div class="page-body">
      <Transition name="router">
        <el-table :data="deviceList" v-if="show === 'device'">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column label="设备名称" width="220">
            <template #default="{ row }">{{ row.customDeviceName || row.name }}</template>
          </el-table-column>
          <el-table-column prop="deviceId" label="设备ID" width="220" />
          <el-table-column prop="ip" label="IP地址" />
          <el-table-column prop="manufacturer" label="厂商" />
          <el-table-column label="设备类型">
            <template #default="{ row }">{{ getDeviceType(row.deviceType) }}</template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-icon 
                size="20" 
                :color="row.onLine ? 'var(--device-online-color)' : 'var(--device-offline-color)'"
                :title="row.onLine ? '在线' : '离线'"
              >
                <Platform />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column prop="streamMode" label="流模式" width="120" />
          <el-table-column prop="transportType" label="传输协议" width="120" />
          <el-table-column label="通道数" width="100">
            <template #default="{ row }">
              <div class="device-channel">
                <span class="count">{{ row.channelCount }}</span>
                <el-icon @click="changeShow('channel', row)" title="查看通道">
                  <View />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button @click="editName(row)" text plain :icon="Edit">编辑</el-button>
              <el-button @click="queryRemove(row)" text type="danger" plain :icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-table :data="channelList" v-else>
          <el-table-column label="通道名称" width="220">
            <template #default="{ row }">{{ row.customChannelName || row.name }}</template>
          </el-table-column>
          <el-table-column prop="channelId" label="通道ID" />
          <el-table-column prop="last_heart_time" label="心跳时间" />
          <el-table-column prop="manufacturer" label="厂商" />
          <el-table-column label="状态">
            <template #default="{ row }">
              <el-icon 
                size="20" 
                :color="row.onLine ? 'var(--device-online-color)' : 'var(--text-color-secondary)'"
                :title="row.onLine ? '在线' : '离线'"
              >
                <Monitor />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" @click="editName(row)" text plain :icon="Edit">编辑</el-button>
              <el-button size="small" @click="queryRemove(row)" text type="danger" plain :icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </Transition>
      
      <el-pagination 
        v-model:current-page="page.current" 
        :page-size="20" 
        layout="prev, pager, next" 
        :total="page.total"
        @current-change="getData" 
      />
    </div>

    <!-- 更改名称对话框 -->
    <el-dialog v-model="edit" width="25%" :title="title">
      <el-form :model="editData" ref="editForm" hide-required-asterisk :rules="editRules" label-width="auto">
        <el-form-item prop="name" :label="(show === 'device' ? '设备' : '通道') + '名称'">
          <el-input v-model="editData.name" />
        </el-form-item>
        <el-form-item v-if="show === 'device'" prop="streamMode" label="流模式">
          <el-select v-model="editData.streamMode">
            <el-option value="UDP" label="UDP"></el-option>
            <el-option value="TCP" label="TCP"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="edit = false">取消</el-button>
        <el-button type="primary" @click="checkEditForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 新增设备对话框 -->
    <el-dialog v-model="insert" width="35%" title="新增设备">
      <el-form :model="insertData" ref="insertForm" hide-required-asterisk :rules="insertRules" label-width="auto">
        <el-form-item prop="name" label="设备名称">
          <el-input v-model="insertData.name" />
        </el-form-item>
        <el-form-item prop="deviceId" label="设备ID">
          <el-input v-model="insertData.deviceId"></el-input>
        </el-form-item>
        <el-form-item prop="channelStartId" label="起始通道ID">
          <el-input v-model="insertData.channelStartId" />
        </el-form-item>
        <el-form-item prop="channelCount" label="通道数量">
          <el-input v-model.number="insertData.channelCount" />
        </el-form-item>
        <el-form-item prop="ip" label="IP地址" v-if="insertData.manufacturer !== 'Other'">
          <el-input v-model="insertData.ip" />
        </el-form-item>
        <el-form-item prop="manufacturer" label="厂商">
          <el-select v-model="insertData.manufacturer" placeholder="请选择厂商">
            <el-option label="海康威视" value="Hikvision"></el-option>
            <el-option label="大华" value="Dahua"></el-option>
            <el-option label="宇视" value="Yushi"></el-option>
            <el-option label="其他" value="Other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="rtspUrl" label="RTSP地址" v-if="insertData.manufacturer === 'Other'">
          <el-input v-model="insertData.rtspUrl" placeholder="rtsp://..." />
        </el-form-item>
        <el-form-item prop="deviceType" label="设备类型">
          <el-select v-model="insertData.deviceType" placeholder="请选择设备类型">
            <el-option label="球机" value="PTZ"></el-option>
            <el-option label="枪机" value="IPC"></el-option>
            <el-option label="录像机" value="NVR"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deviceAccount" label="用户名" v-if="insertData.manufacturer !== 'Other'">
          <el-input v-model="insertData.deviceAccount" />
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="insertData.manufacturer !== 'Other'">
          <el-input v-model="insertData.password" type="password" show-password />
        </el-form-item>
        <el-form-item prop="streamMode" label="流模式">
          <el-select v-model="insertData.streamMode" placeholder="请选择流模式">
            <el-option label="UDP" value="UDP"></el-option>
            <el-option label="TCP-PASSIVE" value="TCP-PASSIVE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="transportType" label="传输协议">
          <el-select v-model="insertData.transportType" placeholder="请选择传输协议">
            <el-option label="RTSP" value="RTSP"></el-option>
            <el-option label="ONVIF" value="ONVIF"></el-option>
            <el-option label="GB28181" disabled value="GB28181"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="checkInsertForm" :loading="insertIng">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Delete, Edit, View, Monitor, Platform } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deviceController } from '@/services/cameraApi'

const loading = ref(false)
const show = ref("device")
const page = reactive({ current: 1, total: 0 })
const deviceList = ref([])
const channelList = ref([])

// 设备类型映射
const getDeviceType = (type) => {
  const typeMap = { PTZ: "球机", IPC: "枪机", NVR: "录像机" }
  return typeMap[type] || type
}

// 获取设备列表
async function getDevices() {
  try {
    loading.value = true
    const { data: { list }, total } = await deviceController.getDeviceList({ page: page.current, count: 20 })

    page.total = total || 0
    if (Array.isArray(list)) {
      deviceList.value = list
    } else {
      deviceList.value = []
    }
  } catch (error) {
    ElMessage.error(error || '获取设备列表失败')
    deviceList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

// 改变显示
async function changeShow(value, row) {
  target.value = row
  deviceId.value = row ? row.deviceId : ""
  show.value = value
  if (value === "device") {
    getDevices()
  } else {
    getChannels()
  }
}

// 改变页码获取数据
function getData() {
  if (show.value === "device") {
    getDevices()
  } else {
    getChannels()
  }
}

// 获取通道
async function getChannels() {
  try {
    loading.value = true
    const { data: { list }, total } = await deviceController.getChannelList({
      page: page.current,
      count: 20,
      deviceId: deviceId.value
    })
    page.total = total || 0
    if (Array.isArray(list)) {
      channelList.value = list
    } else {
      channelList.value = []
    }
  } catch (error) {
    ElMessage.error(error || '获取通道列表失败')
    channelList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

// 新增设备表单
const insertData = ref({
  name: '',
  deviceId: "34020000001320001111",
  channelStartId: "34020000001320001111",
  ip: '',
  manufacturer: '',
  deviceType: '',
  deviceAccount: '',
  password: '',
  streamMode: '',
  rtspUrl: '',
  transportType: '',
  channelCount: 1,
})

// 表单原始备份
const backup = { ...insertData.value }
const insertForm = ref(null)
const insert = ref(false)

// 新增设备
const insertDevice = () => {
  insert.value = true
}

// 校验表单
const checkInsertForm = async () => {
  try {
    await insertForm.value?.validate()
    setData()
  } catch (error) {
    // 验证失败
  }
}

const insertIng = ref(false)

// 确认新增设备
const setData = async () => {
  try {
    insertIng.value = true
    if (insertData.value.manufacturer === 'Other') {
      insertData.value.ip = ""
      insertData.value.deviceAccount = ""
      insertData.value.password = ""
    } else {
      insertData.value.rtspUrl = ""
    }
    const { msg } = await deviceController.addDevice(insertData.value)
    ElMessage.success(msg || '设备添加成功')
    getData()
    cancel()
  } catch (error) {
    ElMessage.error(error || '设备添加失败')
  } finally {
    insertIng.value = false
  }
}

// 取消新增
const cancel = () => {
  insertForm.value?.resetFields()
  insertData.value = { ...backup }
  insert.value = false
}

// 确认移除
const confirmRemove = async (row) => {
  try {
    loading.value = true
    if (show.value === "device") {
      const { msg } = await deviceController.removeDevice({ deviceId: row.deviceId })
      ElMessage.success(msg || '设备删除成功')
    } else {
      const { msg } = await deviceController.removeChannel({
        channelId: row.channelId,
        deviceId: deviceId.value
      })
      ElMessage.success(msg || '通道删除成功')
    }
    getData()
  } catch (error) {
    ElMessage.error(error || '删除失败')
  } finally {
    loading.value = false
  }
}

// 询问删除
const queryRemove = (row) => {
  const title = `确认删除该${show.value === "device" ? "设备" : "通道"}?`
  ElMessageBox.confirm(title, {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => confirmRemove(row)).catch(() => { })
}

// 弹窗标题
const title = ref("")

// 设备id，只有切换通道时才会赋值
const deviceId = ref("")

// 编辑设备名称
const edit = ref(false)
const editForm = ref(null)
const editData = reactive({ name: '', streamMode: "" })
const editName = (row) => {
  title.value = `编辑${show.value === "device" ? "设备" : "通道"}`
  editData.name = row.customDeviceName || row.customChannelName || row.name
  editData.streamMode = row.streamMode || ""
  edit.value = true
  target.value = row
}

// 确认编辑
const confirmEdit = async () => {
  try {
    loading.value = true
    if (show.value === "device") {
      const data = {
        deviceId: target.value.deviceId,
        customDeviceName: editData.name,
        streamMode: editData.streamMode
      }
      const { msg } = await deviceController.editDevice(data)
      ElMessage.success(msg || '设备编辑成功')
    } else {
      const data = {
        channelId: target.value.channelId,
        deviceId: deviceId.value,
        customChannelName: editData.name
      }
      const { msg } = await deviceController.editChannel(data)
      ElMessage.success(msg || '通道编辑成功')
    }
    edit.value = false
    getData()
  } catch (error) {
    ElMessage.error(error || '编辑失败')
  } finally {
    loading.value = false
  }
}

// 编辑的目标
const target = ref()

// 校验编辑表单
const checkEditForm = async () => {
  try {
    await editForm.value?.validate()
    confirmEdit()
  } catch (error) {
    // 验证失败
  }
}

// 校验规则
const editRules = computed(() => ({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  streamMode: [
    { required: true, message: '请选择流模式', trigger: 'blur' },
  ],
}))

// 校验规则
const insertRules = computed(() => ({
  deviceId: [
    { required: true, message: '请输入设备ID', trigger: 'blur' },
    { pattern: /^\d{20}$/, message: '设备ID必须是20位数字', trigger: 'blur' }
  ],
  channelStartId: [
    { required: true, message: '请输入起始通道ID', trigger: 'blur' },
    { pattern: /^\d{20}$/, message: '通道ID必须是20位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
  ],
  manufacturer: [
    { required: true, message: '请选择厂商', trigger: 'blur' },
  ],
  rtspUrl: [
    { required: true, message: '请输入RTSP地址', trigger: 'blur' },
  ],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: 'blur' },
  ],
  deviceAccount: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  streamMode: [
    { required: true, message: '请选择流模式', trigger: 'blur' },
  ],
  transportType: [
    { required: true, message: '请选择传输协议', trigger: 'blur' },
  ],
  channelCount: [
    { required: true, message: '请输入通道数量', trigger: 'blur' },
    { pattern: /(^[1-9]\d*$)/, message: '通道数量必须是正整数', trigger: 'blur' },
  ],
}))

getData()
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.camera-device-page {
  background-color: var(--background-color-page);
  width: 100%;
  height: 100%;
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-md);

  .router-enter-active {
    transition: var(--transition-base);
    transition-delay: 0.3s;
    opacity: 1;
  }

  .router-enter-from,
  .router-leave-to {
    transition: var(--transition-base);
    opacity: 0;
  }

  .router-enter-from {
    transform: translateX(-50px);
  }

  .router-leave-to {
    transform: translateX(50px);
  }

  .page-header {
    .title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 var(--spacing-md);
      border-bottom: 1px solid var(--border-color-lighter);

      span {
        margin-right: auto;
        font-size: var(--font-size-lg);
        font-weight: var(--font-weight-medium);
        color: var(--text-color-primary);
      }
    }
  }

  .page-body {
    height: calc(100% - 72px);

    .el-table {
      height: 100%;

      .device-channel {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-right: var(--spacing-xl);

        .count {
          width: 50%;
          text-align: right;
        }

        .el-icon {
          cursor: pointer;
          color: var(--primary-color);

          &:hover {
            color: var(--primary-light);
          }
        }
      }
    }

    :deep(.el-button.is-text) {
      padding-left: 0;
    }

    .el-pagination {
      justify-content: flex-end;
      margin-top: var(--spacing-lg);
    }
  }

  :deep(.el-form) {
    .el-select {
      width: 100%;
    }
  }

  :deep(.el-dialog) {
    .el-dialog__header {
      padding: var(--spacing-lg) var(--spacing-xl);
      border-bottom: 1px solid var(--border-color-lighter);
    }

    .el-dialog__body {
      padding: var(--spacing-xl);
    }

    .el-dialog__footer {
      padding: var(--spacing-lg) var(--spacing-xl);
      border-top: 1px solid var(--border-color-lighter);
    }
  }
}
</style>
